import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_module/core/hi_flutter_bridge.dart';
import 'package:flutter_module/http/hi_dao.dart';
import 'package:flutter_module/http/hi_error.dart';
import 'package:flutter_module/item/favorite_item.dart';
import 'package:flutter_module/model/common_model.dart';
import 'package:flutter_module/model/goods_model.dart';
import 'package:flutter_module/page/base_page.dart';
import 'package:flutter_module/widget/loading_container.dart';
import 'package:flutter_module/widget/login_widget.dart';

class FavoritePage extends StatefulWidget {
  const FavoritePage({Key key}) : super(key: key);

  @override
  _FavoritePageState createState() => _FavoritePageState();
}

class _FavoritePageState extends BaseState<FavoritePage> with AutomaticKeepAliveClientMixin {
  String header = "";
  int pageIndex = 1;
  bool _loading = true;
  bool _needLogin = false;
  List<GoodsModel> goodsModels;

  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    //获取数据
    _loadData(needCached: false);

    //上拉加载
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _loadData(LoadMore: true);
      }
    });

    //监听native传递事件
    HiFlutterBridge.getInstance().register("onRefresh", (MethodCall call) {
      HiFlutterBridge.getInstance().getHeaderParams().then((value) {
        _loadData();
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    HiFlutterBridge.getInstance().unRegister("onRefresh");
  }

  @override
  Widget build(BuildContext context) {
    return LoadingContainer(
        isLoading: _loading,
        child: !_needLogin
            ? _content
            : LoginWidget(
                loginButtonClick: () {
                  //调起登录
                  HiFlutterBridge.getInstance()
                      .goToNative({"action": "goToLogin"});
                },
              ));
  }

  Future<Null> _handleRfresh() async {
    _loadData();
    return null;
  }

  void _loadData({LoadMore = false, needCached = false}) {
    if (LoadMore) {
      pageIndex++;
    } else {
      pageIndex = 1;
    }
    HiDao.getInstance().favorites(this, (CommonModel model) {
      setState(() {
        _loading = false;
        _needLogin = false;
        List<GoodsModel> items = model.list;
        if (goodsModels != null && pageIndex != 1) {
          goodsModels.addAll(items);
        } else {
          goodsModels = items;
        }
      });
    }, (HiError error) {
      setState(() {
        _loading = false;
      });
      if (error is NeedLogin) {
        setState(() {
          _needLogin = true;
        });
      }
      print(error);
    }, pageIndex: pageIndex, needCached: needCached);
  }

  Widget get _content {
    return RefreshIndicator(
        color: Color(0xffd44949),
        onRefresh: _handleRfresh,
        child: MediaQuery.removePadding(
            removeTop: true,
            context: context,
            child: ListView.builder( //列表优化 不要直接使用ListView
                controller: _scrollController,
                itemCount: goodsModels?.length ?? 0,
                padding: EdgeInsets.only(bottom: 60),
                itemBuilder: (BuildContext context, int index) =>
                    FavoriteItem(index: index, item: goodsModels[index]))));
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
